from api.serializers import DomainTopNModelSerializer, NXDomainRateModelSerializer, QPMModelSerializer
from api.models import DomainTopN, NXDomainRate, QPM
from rest_framework import status as status_code
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import ListModelMixin, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, \
    DestroyModelMixin
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.response import Response
from rest_framework.filters import OrderingFilter
from api.filters import DomainTopNFilter
from api.pagination import CustomPagination
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import AllowAny, IsAuthenticated, IsAdminUser, IsAuthenticatedOrReadOnly
from api.permissions import IsAdminUserOrReadOnly


class DomainTopNListGenericAPIView(GenericAPIView, ListModelMixin, CreateModelMixin):
    queryset = DomainTopN.objects.all()
    serializer_class = DomainTopNModelSerializer

    filter_backends = [DjangoFilterBackend, OrderingFilter]  # part filter
    filterset_class = DomainTopNFilter  # custom filter class

    ordering_fields = ["datetime", "rank"]  # ?ordering=-rank

    pagination_class = CustomPagination  # ?page=2&page_size=n

    authentication_classes = [SessionAuthentication, BasicAuthentication]  # authentication
    permission_classes = [IsAdminUserOrReadOnly]  # permission

    def get(self, request):  # 查询所有item
        return self.list(request)

    def post(self, request):  # 创建单个item
        return self.create(request)


class DomainTopNDetailGenericAPIView(GenericAPIView):
    queryset = DomainTopN.objects.all()
    serializer_class = DomainTopNModelSerializer

    lookup_field = 'datetime'

    def get(self, request, datetime):  # 根据datetime 获取一组数据
        query_set = self.get_queryset()
        instances = query_set.filter(datetime=datetime)
        serializer = self.get_serializer_class()(instance=instances, many=True)
        return Response(serializer.data)

    def delete(self, request, datetime):  # 根据datetime 销毁一组数据
        query_set = self.get_queryset()
        instances = query_set.filter(datetime=datetime)
        for _ in instances:
            self.perform_destroy(_)
        return Response(status=status_code.HTTP_204_NO_CONTENT)

    def perform_destroy(self, instance):
        instance.delete()



